import { delOrganization, getOrgTreeDetailById } from '@/apis/org';
import { Modal, message } from 'antd';
import { useRef, useState } from 'react';

export default function useOrgForm() {
	const [visible, setVisible] = useState(false);
	const [editFormData, setEditFormData] = useState();
	const [loading, setLoading] = useState<boolean>(false);
	const MenuTreeRef = useRef<{
		refresh?: () => void;
	}>();
	const refresh = () => {
		// 刷新
		MenuTreeRef?.current?.refresh?.();
	};
	const handleClose = () => {
		setVisible(false);
	};

	const handleAdd = (data: any) => {
		setEditFormData(data);
		setVisible(true);
	};

	const handleDel = (node: any, reset: () => void) => {
		Modal.confirm({
			title: '提示',
			content: `确定要删除机构【${node.name}】吗`,
			okText: '确定',
			cancelText: '取消',
			centered: true,
			onOk() {
				return new Promise<void>(async (resolve, reject) => {
					try {
						await delOrganization({
							id: node.id,
						});
						message.success('删除机构成功');
						resolve();
						refresh();
						reset?.();
					} catch (error) {
						reject();
						refresh();
					}
				});
			},
		});
	};

	const getOrgDetail = async (node: { id: any }) => {
		setLoading(true);
		try {
			let res: any = await getOrgTreeDetailById({ id: node.id });
			setEditFormData({
				...res,
				id: node.id,
			});
		} finally {
			setLoading(false);
		}
	};

	return {
		visible,
		loading,
		editFormData,
		MenuTreeRef,
		handleAdd,
		handleClose,
		handleDel,
		getOrgDetail,
	};
}
